import React, { Component } from 'react'
import { connect } from 'react-redux'
import { changeAvatar } from '../../store/actions/user'
import {
  Card,
  Button,
  Avatar,
  Upload,
  Spin
} from 'antd'
import axios from 'axios'

const mapState = state => {
  return {
    avatarUrl: state.user.avatar,
    displayName: state.user.displayName,
  }
}

@connect(mapState, { changeAvatar })

class Profile extends Component {
  state = {
    isUploading: false
  }

  handleUploadAvatar = ({ file }) => {
    console.log(file)
    const data = new FormData()
    data.append('Token', '3914d44d4edeffd7cb807fa603e3a7fef60a37be:_hd3KOglhYWOevc34qdIUTbWuGU=:eyJkZWFkbGluZSI6MTU4Mjg1NjkzNCwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzExMDk2IiwiYWlkIjoiMTY2NjcwMiIsImZyb20iOiJmaWxlIn0=')
    data.append('file', file)
    this.setState({
      isUploading: true
    })
    axios.post('http://up.imgapi.com/', data)
      .then(res => {
        console.log(res)
        if (res.status === 200) {
          this.setState({
            isUploading: false
          })
          this.props.changeAvatar(res.data.linkurl)
        } else {
          // 上传失败，处理错误
        }
      })
      .catch(err => {
        // 处理错误
      })
  }

  render() {
    // console.log('Profile', this.props)
    return (
      <div>
        <Card
          title="个人设置" 
          bordered={false}
          extra={<Button >取消</Button>} 
        >
          <Avatar src={this.props.avatarUrl} />
          <span> 欢迎你！{this.props.displayName} </span>

          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader" 
            showUploadList={false}
            customRequest={this.handleUploadAvatar}
          >
            <Spin
              spinning={this.state.isUploading}
            >
              {
                this.props.avatarUrl ? <img style={{height: '100px'}} src={this.props.avatarUrl} alt="头像"/> : <span>点击上传</span>
              }
            </Spin>
          </Upload>
        </Card>
      </div>
    )
  }
}

export default Profile